package tk.mybatis.springboot.common.aop;

import com.jier.aop.ValidateAspectHandel;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import tk.mybatis.springboot.common.message.ResponseData;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.lang.reflect.Method;

/**
 * Created by jie_r on 2017/7/9.
 */
@Component
@Aspect
public class ParamValidate extends ValidateAspectHandel {
    @Override
    public Object error(Method method, String errorMsg) throws Exception {
        //得到方法返回值类型
        Class returnType = method.getReturnType();
        if (returnType == ResponseData.class) {
            //如果返回值为String
            return new ResponseData(1, errorMsg);
        } else if (returnType == ModelAndView.class) {
            //返回错误页面
            ModelAndView modelAndView = new ModelAndView("redirect:error");
            modelAndView.getModel().put("errorMsg", errorMsg);
            return modelAndView;
        } else {
            //当使用Ajax的时候 可能会出现这种情况
            HttpServletResponse res = (HttpServletResponse) args[args.length - 1];
            res.setCharacterEncoding("UTF-8");
            res.setContentType("application/json;charset=utf-8");
            res.setStatus(200);
            PrintWriter printWriter = res.getWriter();
            printWriter.println("{\"code\": 1, \"message\": \"" + errorMsg + "！\"}");
            printWriter.close();
            return null;
        }
    }
}
